package us.mooresr.webtroopmanager.client.activity;

import us.mooresr.webtroopmanager.client.ClientFactory;
import us.mooresr.webtroopmanager.client.TroopManagerService;
import us.mooresr.webtroopmanager.client.TroopManagerServiceAsync;
import us.mooresr.webtroopmanager.client.events.RoleAddedEvent;
import us.mooresr.webtroopmanager.client.place.EditRolePlace;
import us.mooresr.webtroopmanager.client.ui.EditRoleView;
import us.mooresr.webtroopmanager.shared.Role;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;

public class EditRoleActivity extends MyActivity implements EditRoleView.Presenter {
	

	public EditRoleActivity(Place place, ClientFactory clientFactory) {
		super(place, clientFactory);
	}
	
	public void start(AcceptsOneWidget panel, EventBus eventBus) {
		super.start(panel, eventBus);
		
		EditRoleView editRoleView = clientFactory.getEditRoleView();
		editRoleView.setPresenter(this);
		getRole(((EditRolePlace)place).getRoleId());
		panel.setWidget(editRoleView.asWidget());
		
		
	}

	private void getRole(Long roleId) {
		TroopManagerServiceAsync troopManagerService = (TroopManagerServiceAsync) GWT.create(TroopManagerService.class);
		
		if (roleId == null) {
			clientFactory.getEditRoleView().setData(null);
			return;
		}
		
		AsyncCallback<Role> callback = new AsyncCallback<Role>() {
			@Override
			public void onFailure(Throwable caught) {
				clientFactory.getEditRoleView().setData(null);
				
			}
			
			@Override
			public void onSuccess(Role result) {
				clientFactory.getEditRoleView().setData(result);
				
			}
		};
		
		troopManagerService.getRole(roleId, callback);
		
	}

	@Override
	public void addRole(Role role) {
		TroopManagerServiceAsync troopManagerService = (TroopManagerServiceAsync) GWT.create(TroopManagerService.class);
		
		
		AsyncCallback<Role> callback = new AsyncCallback<Role>() {

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onSuccess(Role result) {
				
				clientFactory.getEventBus().fireEvent(new RoleAddedEvent(result));

			}
		};
		
		troopManagerService.addRole(role, callback);
		
	}

}
